package cn.ccenjie.wsy.config;

import cn.ccenjie.wsy.config.jwt.JwtAuthenticationFilter;
import cn.ccenjie.wsy.config.jwt.JwtSuccessHandler;
import cn.ccenjie.wsy.config.vcode.VcodeAuthenticationFilter;
import cn.ccenjie.wsy.properties.WsyAuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.social.security.SpringSocialConfigurer;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private WsyAuthProperties wsyAuthProperties;

    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").failureHandler(jsonRespFailHandler()).successHandler(jwtSuccessHandler())
                .and().authorizeRequests().antMatchers(wsyAuthProperties.getExpath().toArray(new String[0])).permitAll().anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().csrf().disable()
        //super.configure(http);
                .addFilterBefore(vcodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .addFilter(jwtAuthenticationFilter()).apply(springSocialConfigurer());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sysUserDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public SysUserDetailsService sysUserDetailsService() {
        return new SysUserDetailsService();
    }

    /**
     * 验证码过滤器
     * @return
     */
    @Bean
    public VcodeAuthenticationFilter vcodeAuthenticationFilter() {
        return new VcodeAuthenticationFilter();
    }

    @Bean
    public JsonRespFailHandler jsonRespFailHandler() {
        return new JsonRespFailHandler();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }

    @Bean
    public JwtSuccessHandler jwtSuccessHandler() {
        return new JwtSuccessHandler();
    }

    @Bean
    public SpringSocialConfigurer springSocialConfigurer() {
        return new SpringSocialConfigurer();
    }

}
